package com.tanzeer.deliverytracker;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
import java.util.Arrays;
import java.util.Calendar;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.tanzeer.deliverytracker.adapter.IntervalListAdapter;
import com.tanzeer.deliverytracker.dbhelper.RelsellDBOpenHelper;
import com.tanzeer.deliverytracker.functionality.Main;
import com.tanzeer.deliverytracker.utils.PreferenceConnector;

public class SettingsActivity2 extends Activity implements OnClickListener {

	TextView txtrefresh, txtsound, txtsilentstart, txtsilentend;
	LinearLayout layoutrefresh, layoutsound, layoutvibration, layoutsilent,
			layoutsilentstart, layoutsilentend, layoutsave, layoutimport;
	ActionBar actionBar;
	Switch switchsilent;
	CheckBox chkvibratiion;
	TimePickerDialog dialog;
	public static final String DB_NAME="tracking";
	public static int requestCodeForImportTrack = 10001;
	public static int requestCodeForSaveDb = 10002;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.settings_activity_2);
		actionBar = getActionBar();
		actionBar.setTitle("Settings");
		actionBar.setDisplayHomeAsUpEnabled(true);
		txtrefresh = (TextView) findViewById(R.id.textView2);
		txtsound = (TextView) findViewById(R.id.textView4);
		txtsilentstart = (TextView) findViewById(R.id.textView11);
		txtsilentend = (TextView) findViewById(R.id.textView13);

		layoutrefresh = (LinearLayout) findViewById(R.id.layoutrefresh);
		layoutsound = (LinearLayout) findViewById(R.id.layoutnotisound);
		layoutvibration = (LinearLayout) findViewById(R.id.layoutvibration);
		layoutsilent = (LinearLayout) findViewById(R.id.layoutsilent);
		layoutsilentstart = (LinearLayout) findViewById(R.id.layoutsilentstart);
		layoutsilentend = (LinearLayout) findViewById(R.id.layoutsilentend);
		layoutsave = (LinearLayout) findViewById(R.id.layoutsavetracks);
		layoutimport = (LinearLayout) findViewById(R.id.layoutimporttracks);

		chkvibratiion = (CheckBox) findViewById(R.id.checkBox1);

		switchsilent = (Switch) findViewById(R.id.switch1);

		layoutrefresh.setOnClickListener(this);
		layoutsound.setOnClickListener(this);
		layoutsilent.setOnClickListener(this);
		layoutsilentstart.setOnClickListener(this);
		layoutsilentend.setOnClickListener(this);
		layoutvibration.setOnClickListener(this);
		layoutsave.setOnClickListener(this);
		layoutimport.setOnClickListener(this);

		setUI();
	}

	@Override
	protected void onStart() {
		overridePendingTransition(R.anim.anim_in, R.anim.anim_out);
		super.onStart();
	}

	public void setUI() {
		String str = "";
		str = PreferenceConnector.readString(getApplicationContext(),
				PreferenceConnector.Interval, "1 Hour (recommended)");
		txtrefresh.setText(str);
		str = PreferenceConnector.readString(getApplicationContext(),
				PreferenceConnector.RingtoneUri, "1");
		if (str.equals("1")) {
			Uri uri = RingtoneManager.getActualDefaultRingtoneUri(
					getApplicationContext(), RingtoneManager.TYPE_NOTIFICATION);
			Ringtone ringtone = RingtoneManager.getRingtone(
					getApplicationContext(), uri);
			str = ringtone.getTitle(getApplicationContext());
			if (str.equals(""))
				str = "Default sound(Notification)";
		}
		txtsound.setText(str);

		boolean status = PreferenceConnector.readBoolean(
				getApplicationContext(), PreferenceConnector.Vibration, true);
		chkvibratiion.setChecked(status);
		status = PreferenceConnector.readBoolean(getApplicationContext(),
				PreferenceConnector.Silent_MODE, true);
		switchsilent.setChecked(status);
		int hourOfDay = PreferenceConnector.readInteger(
				getApplicationContext(),
				PreferenceConnector.Silent_mode_start_hour, 1);
		int minute = PreferenceConnector.readInteger(getApplicationContext(),
				PreferenceConnector.Silent_mode_start_min, 1);
		String h = "";
		String m = "";
		if (hourOfDay < 10) {
			h = "0" + hourOfDay;

		} else
			h = "" + hourOfDay;
		if (minute < 10) {
			m = "0" + minute;

		} else
			m = "" + minute;
		txtsilentstart.setText(h + ":" + m);
		hourOfDay = PreferenceConnector.readInteger(getApplicationContext(),
				PreferenceConnector.Silent_mode_end_hour, 1);
		minute = PreferenceConnector.readInteger(getApplicationContext(),
				PreferenceConnector.Silent_mode_end_min, 1);
		h = "";
		m = "";
		if (hourOfDay < 10) {
			h = "0" + hourOfDay;

		} else
			h = "" + hourOfDay;
		if (minute < 10) {
			m = "0" + minute;

		} else
			m = "" + minute;

		txtsilentend.setText(h + ":" + m);
		if (!status) {
			layoutsilentstart.setClickable(false);
			layoutsilentend.setClickable(false);
			layoutsilentstart.setBackgroundColor(Color.GRAY);
			layoutsilentend.setBackgroundColor(Color.GRAY);
		} else {
			layoutsilentstart.setClickable(true);
			layoutsilentend.setClickable(true);
			layoutsilentstart.setBackgroundColor(Color.WHITE);
			layoutsilentend.setBackgroundColor(Color.WHITE);

		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		// getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == android.R.id.home) {

			moveBack();

			return true;
		}

		return super.onOptionsItemSelected(item);
	}

	private void moveBack() {
		Intent intent = getIntent();
		int x = intent.getIntExtra("activity", -1);
		// x==0 means it started from main activity and else it is from
		// DeliveryListActivity
		if (x == 0) {
			Intent intentHome = new Intent(getApplicationContext(),
					MainActivity.class);
			intentHome.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intentHome);
			overridePendingTransition(R.anim.anim_in_left, R.anim.anim_out_left);
		}

		else {
			Intent intentHome = new Intent(getApplicationContext(),
					DeliveryListActivity.class);
			intentHome.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			intentHome.putExtra("type",
					getIntent().getStringExtra("contenttype"));
			intentHome.putExtra("value", 1);
			startActivity(intentHome);
			overridePendingTransition(R.anim.anim_in_left, R.anim.anim_out_left);

		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (resultCode == Activity.RESULT_OK && requestCode == 5) {
			Uri uri = data
					.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);

			if (uri != null) {
				String chosenRingtone = uri.toString();
				RingtoneManager.setActualDefaultRingtoneUri(this,
						RingtoneManager.TYPE_NOTIFICATION, uri);
				//
				// toast(chosenRingtone);
				Ringtone ringtone = RingtoneManager.getRingtone(
						getApplicationContext(), uri);
				PreferenceConnector.writeString(getApplicationContext(),
						PreferenceConnector.RingtoneUri,
						ringtone.getTitle(getApplicationContext()));
				setUI();
			}

		} else if (resultCode == Activity.RESULT_OK && requestCode == requestCodeForImportTrack) {
			String fileToImportPath = null;
			if (data != null) {
				fileToImportPath = data.getStringExtra("fileToImportPath");
			}
			
			final String filePathToImportDbFrom = fileToImportPath;
			
			new AlertDialog.Builder(this)
		    .setTitle("Import DB")
		    .setMessage("Are you sure you want to Import Tracking DB ?")
		    .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
		        public void onClick(DialogInterface dialog, int which) { 
		        	RelsellDBOpenHelper rHelper = new RelsellDBOpenHelper(SettingsActivity2.this);
		        	rHelper.dropDBTables();
		        	String filePath = importDbFromBackup(SettingsActivity2.this,filePathToImportDbFrom);
		        	Toast.makeText(SettingsActivity2.this, "Your DB imported at: "+filePath, Toast.LENGTH_SHORT).show();
		        }
		     })
		    .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
		        public void onClick(DialogInterface dialog, int which) { 
		            // do nothing
		        }
		     })
		    .setIcon(android.R.drawable.ic_dialog_alert)
		     .show();
		}  else if (resultCode == Activity.RESULT_OK && requestCode == requestCodeForSaveDb) {
			String saveDbToPath = null;
			if (data != null) {
				saveDbToPath = data.getStringExtra("saveDbToPath");
			}
			if (saveDbtoBackupFile(SettingsActivity2.this, saveDbToPath)) {
				Toast.makeText(SettingsActivity2.this,
						"Your DB exported at: " + saveDbToPath,
						Toast.LENGTH_SHORT).show();
			}
		}
	}

	@Override
	public void onClick(View v) {

		if (v.getId() == R.id.layoutrefresh) {
			showIntervalDialog();
		} else if (v.getId() == R.id.layoutnotisound) {
			Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
			intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE,
					RingtoneManager.TYPE_NOTIFICATION);
			intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, "Select Tone");
			Uri uri = RingtoneManager.getActualDefaultRingtoneUri(
					getApplicationContext(), RingtoneManager.TYPE_NOTIFICATION);
			intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, uri);
			startActivityForResult(intent, 5);
		} else if (v.getId() == R.id.layoutvibration) {
			if (chkvibratiion.isChecked())
				chkvibratiion.setChecked(false);
			else
				chkvibratiion.setChecked(true);
			PreferenceConnector.writeBoolean(getApplicationContext(),
					PreferenceConnector.Vibration, chkvibratiion.isChecked());

		} else if (v.getId() == R.id.layoutsilent) {

			if (switchsilent.isChecked())
				switchsilent.setChecked(false);
			else
				switchsilent.setChecked(true);
			PreferenceConnector.writeBoolean(getApplicationContext(),
					PreferenceConnector.Silent_MODE, switchsilent.isChecked());
			setUI();

		} else if (v.getId() == R.id.layoutsavetracks) {
			Intent i = new Intent(SettingsActivity2.this,Main.class);
			i.putExtra("caller","savedb");
			SettingsActivity2.this.startActivityForResult(i, requestCodeForSaveDb );
			overridePendingTransition(R.anim.anim_in,R.anim.anim_out);
		} else if (v.getId() == R.id.layoutimporttracks) {
			
			Intent i = new Intent(SettingsActivity2.this,Main.class);
			i.putExtra("caller","importdb");
			SettingsActivity2.this.startActivityForResult(i, requestCodeForImportTrack );
			overridePendingTransition(R.anim.anim_in,R.anim.anim_out);
			
		} else if (v.getId() == R.id.layoutsilentstart) {
			final Calendar c = Calendar.getInstance();

			int hour = PreferenceConnector.readInteger(this,
					PreferenceConnector.Silent_mode_start_hour,
					c.get(Calendar.HOUR_OF_DAY));
			int minute = PreferenceConnector.readInteger(this,
					PreferenceConnector.Silent_mode_start_min,
					c.get(Calendar.MINUTE));
			showDialogStart(hour, minute);

		} else if (v.getId() == R.id.layoutsilentend) {
			final Calendar c = Calendar.getInstance();

			int hour = PreferenceConnector.readInteger(this,
					PreferenceConnector.Silent_mode_end_hour,
					c.get(Calendar.HOUR_OF_DAY));
			int minute = PreferenceConnector.readInteger(this,
					PreferenceConnector.Silent_mode_end_min,
					c.get(Calendar.MINUTE));
			showDialogEnd(hour, minute);

		}

	}

	private void showIntervalDialog() {
		final Dialog dialog = new Dialog(SettingsActivity2.this);
		dialog.setTitle("Refresh Interval");
		dialog.setContentView(R.layout.dialog_refresh_interval);

		TextView tv = (TextView) dialog.findViewById(R.id.textView1);
		ListView lv = (ListView) dialog.findViewById(R.id.listView1);
		final String[] list = { "5 Minutes", "15 Minutes ", "30 Minutes",
				"1 Hour (recommended)", "2 Hours", " 4 Hours", "6 Hours",
				"12 Hours", "1 day" };
		IntervalListAdapter adapter = new IntervalListAdapter(
				getApplicationContext(), R.layout.interval_list_row,
				Arrays.asList(list));
		lv.setAdapter(adapter);
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long id) {

				RadioButton radioButton = (RadioButton) v
						.findViewById(R.id.radioButton1);
				if (radioButton.isChecked())
					radioButton.setChecked(false);
				else
					radioButton.setChecked(true);
				PreferenceConnector.writeString(getApplicationContext(),
						PreferenceConnector.Interval, list[position]);
				dialog.dismiss();
				setUI();

			}
		});
		tv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.dismiss();

			}
		});
		dialog.show();
	}

	private void showDialogStart(int hour, int min) {
		dialog = new TimePickerDialog(SettingsActivity2.this,
				new OnTimeSetListener() {

					@Override
					public void onTimeSet(TimePicker view, int hourOfDay,
							int minute) {

						PreferenceConnector.writeInteger(
								getApplicationContext(),
								PreferenceConnector.Silent_mode_start_hour,
								hourOfDay);
						PreferenceConnector.writeInteger(
								getApplicationContext(),
								PreferenceConnector.Silent_mode_start_min,
								minute);
						setUI();
						// dialog.dismiss();

					}
				}, hour, min, true);
		dialog.show();
	}

	private void showDialogEnd(int hour, int min) {
		dialog = new TimePickerDialog(SettingsActivity2.this,
				new OnTimeSetListener() {

					@Override
					public void onTimeSet(TimePicker view, int hourOfDay,
							int minute) {
						PreferenceConnector.writeInteger(
								getApplicationContext(),
								PreferenceConnector.Silent_mode_end_hour,
								hourOfDay);
						PreferenceConnector
								.writeInteger(
										getApplicationContext(),
										PreferenceConnector.Silent_mode_end_min,
										minute);
						setUI();

					}
				}, hour, min, true);
		dialog.show();
	}

	@Override
	public void onBackPressed() {
		moveBack();

	}
	
	public String importDbFromBackup(Context context,String backupfilePath) {
			try {
				File sd = Environment.getExternalStorageDirectory();
				String actualFilePath = backupfilePath.substring(sd.getAbsolutePath().length()+1);
				
				File data = Environment.getDataDirectory();
				String backupDBPath = "/data/"+context.getPackageName()
						+ "/databases/"+DB_NAME;
				File currentDB = new File(sd,actualFilePath);
				File backupDB = new File(data, backupDBPath);
				FileChannel src = new FileInputStream(currentDB).getChannel();
				FileChannel dst = new FileOutputStream(backupDB).getChannel();
				Log.v("TAG", "bytes transferred "+dst.transferFrom(src, 0, src.size()));
				src.close();
				dst.close();
				return backupDBPath;
				
			} catch (Exception e) {
				Log.v("TAG", "exception "+e);
				
				return null;

			}
	}
	
	public boolean saveDbtoBackupFile(Context context,String saveFilePath) {
		boolean result = false;
		try {
			File sd = new File(saveFilePath);
			
			File data = Environment.getDataDirectory();
			if (sd.canWrite()) {
				String currentDBPath = "/data/"
						+ context.getPackageName() + "/databases/" + DB_NAME;
				String backupDBPath = DB_NAME + ".sqlite";
				File currentDB = new File(data,currentDBPath);
				File backupDB = new File(sd, backupDBPath);
				FileChannel src = new FileInputStream(currentDB).getChannel();
				FileChannel dst = new FileOutputStream(backupDB).getChannel();
				dst.transferFrom(src, 0, src.size());
				src.close();
				dst.close();
				result = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
			result = false;
		}
		
		
		return result;
		
	}
	

}
